package com.easy.service.impl;

import com.easy.bean.PostBean;
import com.easy.bean.UserBean;
import com.easy.mapper.UserDao;
import com.easy.service.LoginService;
import com.easy.util.LogMethod;
import com.easy.util.PasswordUtil;
import com.easy.util.SYS;
import com.easy.util.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    UserDao userDao;
    @Override
    @LogMethod(serviceName = "用户登录",recordReturn = true)
    public String login(UserBean user) {
        //登录逻辑
        //1、通过用户名查询数据库
        UserBean result = userDao.getByNumber(user.getUserNumber());
        if(result==null){
            System.out.println("用户名"+result);
            throw new RuntimeException("用户不存在");
        }
        //2、验证密码
        String password =user.getUserPassword();
        String encryptionPassword = result.getUserPassword();
        System.out.println(password);
        System.out.println(encryptionPassword);
        if(!PasswordUtil.checkPassword(password,encryptionPassword)){
            System.out.println("密码判断"+PasswordUtil.checkPassword(password,encryptionPassword));
            throw new RuntimeException("密码错误");
        }
        //3、返回结果token
        String token= TokenUtil.getToken(result.getId(),result.getRole());
        return token;
    }

    @Override
    public UserBean loginInfo(String token) {
        Object id = TokenUtil.getOption(token,SYS.TOKEN_ID);
        if (id==null){
            System.out.println(id);
            throw new RuntimeException("登录异常");
        }
        UserBean user = userDao.get(Integer.parseInt(id.toString()));
        return user;
    }

}
